package com.cdream.basic.thread.pattern;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author cdream
 * @date 2022/2/6
 */
@Slf4j(topic = "two-phase")
public class TwoPhaseInterrupt {
    public static void main(String[] args) {
        TwoPhaseTermination thread = new TwoPhaseTermination();
        thread.start();
        ThreadUtil.sleep(5000);
        thread.stop();
    }
}

@Slf4j(topic = "two-phase.termination")
class TwoPhaseTermination {
    private Thread monitor;

    public void start() {
        monitor = new Thread(() -> {
            Thread thread = Thread.currentThread();
            while (true) {
                if (thread.isInterrupted()) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                    log.debug("执行监控");
                } catch (Exception e) {
                    log.debug(e.getMessage());
                    // sleep 打断会清除标记
                    thread.interrupt();
                }
            }
        },"monitor");
        monitor.start();
    }

    public void stop() {
        monitor.interrupt();
    }
}
